<template>
	<view class="container">
		<view class="time-selector">
		    <view class="time-selector-title"> {{ curTime }} 数据时间</view>
			<view
				v-if="timeList!=''" class="time-tabs" style="margin-top: 5px;">
				<view
					:class="[
						'time-tab',
						item.code == curData ? 'active' : '',
					]"
					v-for="(item, index) in timeList"
					:key="index"
					:data-time="item"
					@click="selectTime(item.code)"
				>
					{{ item.name }}
				</view>
			</view>
			<view v-if="curData == 'zidingyi'">
				<uni-datetime-picker type="year-month" fields="month" :end='endTime' :clear-icon="false" v-model="zdyTime" @change='timeChange' />
			</view>
		</view>
		<!-- 功能投用率主卡片 -->
		<view class="main-card">
		    <view class="main-card-title">功能投用率总览</view>
		    <view class="utilization-grid">
		        <view 
				v-for="(item, index) in utilData"
				:key = 'index'
				class="utilization-item">
		            <view class="utilization-label">{{ item.name }}</view>
		            <view class="utilization-value">{{ item.value }}
					<label class="utilization-unit">%</label></view>
		        </view>
		    </view>
		    <view class="chart-mini">
				<qiun-data-charts 
					 :canvas-style="canvasStyle" 
				      type="ring"
					  :canvas2d="true"
				      :opts="opts"
				      :chartData="chartData"
				    />
			</view>
		</view>
		<!-- 设备异常情况 -->
		<view class="equipment-section">
		    <view class="section-title">重点管控设备异常</view>
		   <view class="equipment-grid">
		     <view class="equipment-card"
		          :class="item.state ? item.state : 'pranmy'"
		          v-for="(item, index) in equipmentData"
		          :key="index"
		          @click="showEquipmentDetail(item)">
		       <view class="equipment-header">
		         <view class="equipment-name">
		           <span class="status-dot" :class="'status-' + (item.state || 'pranmy')"></span>
		           {{ item.name }}
		         </view>
		         <view class="equipment-count" :class="item.state || 'pranmy'">{{ item.count }}</view>
		       </view>
		       <view class="equipment-unit">项功能异常</view>
		       <view class="equipment-detail">{{ item.desc }}</view>
		     </view>
		   </view>
		</view>
		<!-- 设备详情弹窗 -->
		<!-- equipmentModal.wxml -->
		 <!-- uni-popup 弹窗 -->
		 <uni-popup ref="popup" type="center" :mask-click="true">
		   <view class="popup-wrapper" style="width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center;">
		     <view class="popup-content" style="width: 100%; max-width: 100%;">
		       <view class="modal-content">
					<view class="modal-header">
					  <view class="modal-title">{{modalTitle}}</view>
					  <button class="close-btn" @click="closeModal">×</button>
					</view>
					<view class="modal-body">
					  <view class="detail-list" 
					  v-if="detailList.length > 0"
					  v-for="(item, timeKey) in detailList"
					  :key="timeKey">
					    <view class="detail-item">
					      <view class="detail-info">
					        <view class="detail-function">{{item.function}}</view>
					        <view class="detail-desc">{{item.desc}}</view>
					      </view>
					      <view class="detail-count">{{item.count}}{{item.unit}}</view>
					    </view>
					  </view>
					</view>
					<view style="text-align: center;padding-bottom: 20px;" v-if="detailList.length == 0">暂无数据</view>
		       </view>
		     </view>
		   </view>
		 </uni-popup>
		<view class="modal" v-if="closeModal">
		</view>
		<!-- 图表展示区域 -->
		<view class="chart-section">
		    <view class="chart-header">
		        <view class="chart-title">异常趋势分析</view>
		        <view class="chart-time-selector">
					<uni-datetime-picker v-model="rangeTime" :end='endTime' type="daterange" :clear-icon="false" @change='rangeChange'/>
		        </view>
		    </view>
		    <view class="chart-container">
				<qiun-data-charts
					 :canvas-style="canvasStyle" 
				      type="line"
					  :canvas2d="true"
				      :opts="optsLine"
					  :reshow="isShow"
				      :chartData="lineData"
				    />
			</view>
		</view>
		<!-- 底部安全区域 -->
		<view class="safe-area"></view>
	</view>
</template>

<script>
import { timestampFormatDate } from '../../../utils/FormatTime.js'
import { post, postForm } from '@/utils/request';
import { getFuncAnomaly, getFuncUtilizationRate, getAnomalyTrend } from '@/api/check.js';
export default {
	name: '',
	data() {
		return {
			isShow: false,
			endTime: Date.now(),
			zdyTime: Date.now(),
			echartsView: true,
			curTime: Date.now(),
			popupType: 'bottom',
			canvasStyle: {
			      zIndex: 1,
			    },
			rangeTime: [Date.now() - 7*24*3600*1000, Date.now()],
			chartData: {},
			lineData: {},
			showModal: false,
			modalTitle: "",
			detailList: [],
			curData: 'today',
			opts: {
				fontColor: "#FFFFFF",
				rotate: false,
				subtitle: false,
				rotateLock: false,
				color: ["#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
				padding: [5,5,5,5],
				dataLabel: true,
				enableScroll: false,
				legend: {
					show: true,
					position: "right",
					lineHeight: 25
					},
				title: false,
				tooltip: {
					show: true,
					triggerOn: 'hover',
					},
				extra: {
					ring: {
						ringWidth: 30,
						labelWidth: 0,
						labelLine: false,
						border: false,
						centerColor: "#1890FF",
						backgroundColor: "#1890FF"
					},
				pie: {
					activeOpacity: 0.7,
					labelWidth: 0,
					labelLine: false,
					labelColor: '#ffffff',
					activeRadius: 8,
					label: {
						show: true,
						fontColor: '#ffffff',
						fontSize: 14,
						position: 'outside'
						}
					}
				}
			},
			optsLine: {
			  color: ["#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
			  padding: [0, 20, 20, 0],
			  dataLabel: false,
			  dataPointShape: false,
			  enableScroll: false,
			  legend: {
			      position: 'top'
			  },
			  xAxis: {
			    disableGrid: true,
			    marginTop: 5,
			    scrollShow: false,
				padding: [0, 20], // 文字自身的上下左右留白 [!code focus]
				offset: 15,         // 轴线距离图表容器底部的距离 [!code focus]
				fontSize: 12,       // 文字大小（影响整体占位）
			    labelCount: 6, // [!code focus]
				gridEval: 5,
				boundaryGap: 'justify'  // 均匀分布模式
			  },
			  yAxis: {
			    gridType: "dash",
			    dashLength: 2
			  },
			  extra: {
			    line: {
			      type: "curve",
			      width: 2,
			      activeType: "hollow",
			    }
			  }
			},
			timeList: [
				{
					code: 'today',
					name: '今日'
				},
				{
					code: 'yesterday',
					name: '前一天'
				},
				{
					code: 'zidingyi',
					name: '自定义'
				}
			],
			timeData: {},
			utilData: [],
			equipmentData: [],
		};
	},
	
	watch: {
	},
	onLoad(option) {
	},
	onShow() {
		this.curTime = Date.now()
		this.zdyTime = Date.now() - 2*24*3600*1000
		this.curTime = timestampFormatDate(this.curTime, 'yyyy-MM-dd')
		this.zdyTime = timestampFormatDate(this.zdyTime, 'yyyy-MM-dd')
		let start = Date.now() - 7*24*3600*1000
		let end = Date.now()
		this.rangeTime = [timestampFormatDate(start, 'yyyy-MM-dd hh:mm:ss'),timestampFormatDate(end, 'yyyy-MM-dd hh:mm:ss')]
		this.getData()
		this.getLine()
	},
	methods: {
		selectTime(time) {
			let timeData = ''
			if(time != 'zidingyi') {
				if(time == 'today') {
					timeData = Date.now()
					this.curTime = timestampFormatDate(timeData, 'yyyy-MM-dd')
				} else if(time == 'yesterday') {
					timeData = Date.now() - 1*24*3600*1000
					this.curTime = timestampFormatDate(timeData, 'yyyy-MM-dd')
				}
			} else {
					timeData = this.zdyTime
					this.curTime = timeData
				}
			this.curData = time
			this.getData()
		},
		async getData() {
			uni.showLoading({
				title: '数据加载中！',
				mask: true,
			});
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				queryTime: this.curTime
			}
			const res = await getFuncAnomaly(dataParams);
			uni.hideLoading();
			let resData = res.data
			for(var i=0; i< resData.length; i++) {
				if(resData[i].count > 0) {
					resData[i].state = 'warning'
				} else {
					resData[i].state = 'normal'
				}
			}
			this.equipmentData = resData
			const res1 = await getFuncUtilizationRate(dataParams);
			uni.hideLoading();
			this.utilData = res1.data
			let ser = res1.data
			this.bingCharts(ser)
		},
		bingCharts(midData) {
			 let res = {
			     series: [
			       {
			         data: midData
			       }
			     ]
			   };
			 this.chartData = JSON.parse(JSON.stringify(res));
		},
		timeChange() {
			this.curTime = this.zdyTime
			this.getData()
		},
		rangeChange() {
			this.getLine()
		},
		async getLine() {
			const userInfor = uni.getStorageSync('userInfor');
			const dataParams = {
				userId: userInfor.userId,
				startTime: this.rangeTime[0],
				endTime: this.rangeTime[1]
			}
			const res = await getAnomalyTrend(dataParams);
			let resData = res.data
			let dataLength = res.data.categories.length
			if(dataLength > 10) {
				this.optsLine.xAxis.labelCount = 4
			} else if(dataLength == 10) {
				this.optsLine.xAxis.labelCount = 3
			} else {
				this.optsLine.xAxis.labelCount = 6
			}
			this.confirmDateRange(resData)
		},
		change() {},
		confirmDateRange(res) {
			this.lineData = JSON.parse(JSON.stringify(res));
			this.isShow = true
			this.isShow = false
		},
		showEquipmentDetail(data) {
		    const details = data.subItem || [];
		    this.modalTitle = data.name + " 详细异常";
		    this.detailList = details;
			this.$refs.popup.open();
		  },
		  
		  closeModal() {
			this.$refs.popup.close();
		  },
	},
}
</script>
<style>
</style>
<style scoped lang="scss">
	.container {
		padding: 12px;
	}
 /* 时间筛选器 */
        .time-selector {
            background: white;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
            border: 1px solid #f0f0f0;
        }

        .time-selector-title {
            font-size: 14px;
            font-weight: 600;
            color: #262626;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
        }

        .time-selector-title::before {
            content: '📅';
            margin-right: 8px;
            font-size: 16px;
        }

        .time-tabs {
            display: flex;
            background: #f5f5f5;
            border-radius: 8px;
            padding: 4px;
            gap: 4px;
        }

        .time-tab {
            flex: 1;
            text-align: center;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 500;
            color: #8c8c8c;
            transition: all 0.2s ease;
            cursor: pointer;
        }

        .time-tab:active {
            transform: scale(0.98);
        }

        .time-tab.active {
            background: #1890ff;
            color: white;
            box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
        }
		/* 功能投用率大卡片 */
		.main-card {
		    background: linear-gradient(135deg, #1890ff, #096dd9);
		    border-radius: 16px;
		    padding: 20px;
		    margin-bottom: 16px;
		    color: white;
		    box-shadow: 0 8px 24px rgba(24, 144, 255, 0.15);
		}
		
		.main-card-title {
		    font-size: 18px;
		    font-weight: 600;
		    margin-bottom: 16px;
		    display: flex;
		    align-items: center;
		}
		
		.main-card-title::before {
		    content: '📊';
		    margin-right: 8px;
		    font-size: 20px;
		}
		
		.utilization-grid {
		    display: grid;
		    grid-template-columns: repeat(2, 1fr);
		    gap: 12px;
		    margin-bottom: 16px;
		}
		
		.utilization-item {
		    background: rgba(255, 255, 255, 0.15);
		    backdrop-filter: blur(10px);
		    border-radius: 12px;
		    padding: 8px 5px;
		    text-align: center;
		    border: 1px solid rgba(255, 255, 255, 0.2);
		}
		
		.utilization-label {
		    font-size: 12px;
		    opacity: 0.9;
		    margin-bottom: 4px;
		}
		
		.utilization-value {
		    font-size: 20px;
		    font-weight: 700;
		    margin-bottom: 2px;
		}
		
		.utilization-unit {
		    font-size: 10px;
		    opacity: 0.8;
		}
		
		.chart-mini {
		    height: 250px;
		    background: rgba(255, 255, 255, 0.1);
		    border-radius: 12px;
		    margin-top: 12px;
		}
		/* 设备异常卡片 */
		.equipment-section {
		    margin-bottom: 16px;
		}
		
		.section-title {
		    font-size: 16px;
		    font-weight: 600;
		    color: #262626;
		    margin-bottom: 12px;
		    display: flex;
		    align-items: center;
		}
		
		.section-title::before {
		    content: '⚠️';
		    margin-right: 8px;
		    font-size: 18px;
		}
		
		.equipment-grid {
		    display: grid;
		    grid-template-columns: repeat(2, 1fr);
		    gap: 12px;
		}
		/* 定义不同状态的样式 */
		.equipment-card {
		  background: white;
		  border-radius: 12px;
		  padding: 16px;
		  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		  border: 1px solid #f0f0f0;
		  transition: all 0.2s ease;
		  position: relative;
		  overflow: hidden;
		  
		  &::before {
		    content: '';
		    position: absolute;
		    top: 0;
		    left: 0;
		    right: 0;
		    height: 3px;
		  }
		  
		  &.normal {
		    &::before {
		      background: linear-gradient(90deg, #52c41a, #389e0d);
		    }
		  }
		  
		  &.warning {
		    &::before {
		      background: linear-gradient(90deg, #faad14, #fa8c16);
		    }
		  }
		  
		  &.error {
		    &::before {
		      background: linear-gradient(90deg, #ff4d4f, #cf1322);
		    }
		  }
		  &.pranmy::before {
			  background: linear-gradient(90deg, #1890ff, #1890ff);
		  }
		}
		
		.equipment-header {
		    display: flex;
		    align-items: center;
		    justify-content: space-between;
		    margin-bottom: 8px;
		}
		
		.equipment-name {
		    font-size: 14px;
		    font-weight: 600;
		    color: #262626;
		    display: flex;
		    align-items: center;
		}
		.status-dot {
		  width: 6px;
		  height: 6px;
		  border-radius: 50%;
		  margin-right: 6px;
		  
		  &.status-normal {
		    background-color: #52c41a;
		  }
		  
		  &.status-warning {
		    background-color: #faad14;
		  }
		  
		  &.status-error {
		    background-color: #ff4d4f;
		  }
		  &.status-pranmy {
		    background-color: #1890ff;
		  }
		}
		
		.equipment-count {
		  font-weight: bold;
		  
		  &.normal {
		    color: #52c41a;
		  }
		  
		  &.warning {
		    color: #faad14;
		  }
		  &.error {
		    color: #ff4d4f;
		  }
		}
		.equipment-unit {
		    font-size: 11px;
		    color: #8c8c8c;
		    margin-top: 2px;
		}
		
		.equipment-detail {
		    font-size: 12px;
		    color: #595959;
		    margin-top: 8px;
		    padding-top: 8px;
		    border-top: 1px solid #f0f0f0;
		}
		/* 图表区域 */
		.chart-section {
		    background: white;
		    border-radius: 12px;
		    padding: 14px;
		    margin-top: 16px;
		    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		    border: 1px solid #f0f0f0;
		}
		
		.chart-header {
		}
		
		.chart-title {
		    font-size: 14px;
		    font-weight: 600;
		    color: #262626;
		    align-items: center;
			margin-bottom: 5px;
		}
		
		.chart-title::before {
		    content: '📈';
		    margin-right: 8px;
		}
		
		.chart-time-selector {
		    align-items: center;
		    gap: 8px;
		}
		
		.date-range-picker {
		    display: flex;
		    align-items: center;
		    gap: 4px;
		    background: #f5f5f5;
		    border-radius: 6px;
		    padding: 4px 8px;
		    font-size: 14px;
		    color: #666;
		}
		
		.date-input {
		    border: none;
		    background: transparent;
		    font-size: 11px;
		    color: #666;
		    width: 80px;
		    text-align: center;
		    outline: none;
		}
		
		.date-separator {
		    color: #999;
		    margin: 0 2px;
		}
		
		.date-confirm-btn {
		    background: #1890ff;
		    color: white;
		    border: none;
		    border-radius: 4px;
		    padding: 2px 6px;
		    font-size: 10px;
		    cursor: pointer;
		    margin-left: 4px;
		    transition: all 0.2s ease;
		}
		
		.date-confirm-btn:active {
		    transform: scale(0.95);
		    background: #096dd9;
		}
		
		.chart-container {
		    height: 250px;
		}
		/* 模态框适配小程序 */
		.modal {
		    display: none;
		    position: fixed;
		    z-index: 1000;
		    left: 0;
		    top: 0;
		    width: 100%;
		    height: 100%;
		    background: rgba(0, 0, 0, 0.6);
		}
		.popup-wrapper {
		  position: relative;
		  width: 100vw;
		  height: 100vh;
		  display: flex;
		  justify-content: center;
		  align-items: center;
		}
		
		.popup-content {
		  width: 100% !important;
		  max-width: 100% !important;
		  height: auto;
		  margin: 0;
		  border-radius: 0;
		}
		
		.modal-content {
		  width: 100%;
		  max-height: 80vh;
		  background: white;
		  border-radius: 16px 16px 16px 16px;
		  overflow: hidden;
		}
		
		@keyframes slideUp {
		    from { transform: translateY(100%); }
		    to { transform: translateY(0); }
		}
		
		.modal-header {
		  padding: 16px;
		  border-bottom: 1px solid #f0f0f0;
		  display: flex;
		  align-items: center;
		  justify-content: space-between; /* 确保标题和按钮分居两侧 */
		  background: #fafafa;
		  position: relative; /* 新增：为绝对定位提供参照 */
		}
		
		.modal-title {
		  font-size: 16px;
		  font-weight: 600;
		  color: #262626;
		  flex: 1; /* 新增：标题占据剩余空间 */
		  text-align: center; /* 可选：标题居中 */
		}
		
		.close-btn {
		  width: 28px;
		  height: 28px;
		  border-radius: 50%;
		  background: #f5f5f5;
		  border: none;
		  display: flex;
		  align-items: center;
		  justify-content: center;
		  font-size: 16px;
		  color: #8c8c8c;
		  cursor: pointer;
		  position: absolute; /* 改为绝对定位 */
		  right: 16px; /* 距离右侧16px */
		  top: 50%; /* 垂直居中 */
		  transform: translateY(-50%); /* 垂直居中修正 */
		  z-index: 1; /* 确保在标题上方 */
		}
		
		.modal-body {
		    padding: 16px;
		    max-height: 400px;
		    overflow-y: auto;
		}
		
		.detail-list {
		    display: flex;
		    flex-direction: column;
		    gap: 12px;
		}
		
		.detail-item {
		    background: #fafafa;
		    border-radius: 8px;
		    padding: 12px;
		    display: flex;
		    justify-content: space-between;
		    align-items: center;
		    border-left: 3px solid #1890ff;
		}
		
		.detail-info {
		    flex: 1;
		}
		
		.detail-function {
		    font-size: 14px;
		    font-weight: 500;
		    color: #262626;
		    margin-bottom: 2px;
		}
		
		.detail-desc {
		    font-size: 12px;
		    color: #8c8c8c;
		}
		
		.detail-count {
		    font-size: 16px;
		    font-weight: 700;
		    color: #1890ff;
		    text-align: right;
		}
		/* 底部安全区域 */
		.safe-area {
		    height: 20px;
		}
		
		/* 加载状态 */
		.loading {
		    display: flex;
		    align-items: center;
		    justify-content: center;
		    height: 100px;
		    color: #8c8c8c;
		    font-size: 14px;
		}
		
		.loading::before {
		    content: '';
		    width: 16px;
		    height: 16px;
		    border: 2px solid #f0f0f0;
		    border-top-color: #1890ff;
		    border-radius: 50%;
		    animation: spin 1s linear infinite;
		    margin-right: 8px;
		}
		
		@keyframes spin {
		    to { transform: rotate(360deg); }
		}
		
		/* 空状态 */
		.empty-state {
		    text-align: center;
		    padding: 40px 20px;
		    color: #8c8c8c;
		}
		
		.empty-state::before {
		    content: '📭';
		    font-size: 32px;
		    display: block;
		    margin-bottom: 8px;
		}
</style>
